import { isFunction } from "./share";

export default abstract class Xhr {
    private getXMLHttpRequest() {
        let xhr = new XMLHttpRequest();
        // 如果存在低端浏览器需求场景，请放开一下注释代码
        // if (xhr == null) {
        //     xhr = new ActiveXObject("Microsoft.XMLHTTP");
        // }
        return xhr;
    }
    private setHeader(xhr: any, key: string, value: string) {
        xhr.setRequestHeader(key, value);
    }
    private getRequestParameter(config: any) {
        if (
            config.headers["Content-Type"] ===
            "application/x-www-form-urlencoded"
        ) {
            let formdata: any[] = [];
            Object.keys(config.data || {}).map((k: string) =>
                formdata.push(k.concat("=", encodeURIComponent(config.data[k]) ))
            );
            return formdata.join("&");
        } else return config.data;
    }
    private ready(xhr: any, config: any) {
        xhr.timeout = config.timeout;

        for (var k in config.headers) {
            if (config.headers[k] !== "multipart/form-data") {
                this.setHeader(xhr, k, config.headers[k]);
            }
        }

        return xhr;
    }
    private createXHR(config: any) {
        let xhr = this.getXMLHttpRequest();
        let Parameter = this.getRequestParameter(config);
        //console.log(Parameter)
        if (
            config.type.toLowerCase() == "get" && Parameter
        ) {
            config.url += "?" + Parameter;
        }
        xhr.open(config.type, config.url, config.async);
        this.ready(xhr, config).send(Parameter);
        return xhr;
    }
    xmlRequest(config: any) {
        let xhr = this.createXHR(config);
        if (xhr != null) {
            xhr.onreadystatechange = function() {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    isFunction(config.success) && config.success(xhr);
                } else if (xhr.readyState === 4) {
                    isFunction(config.error) && config.error(xhr);
                }
            };
        } else {
            isFunction(config.error) &&
            config.error("Your browser does not support XMLHTTP.");
        }
    }
    async xmlRequestAsync(config: any) {
        let xhr = this.createXHR(config);
        if (xhr != null) {
            return await new Promise((reslove, reject) => {
                xhr.onreadystatechange = () => {
                    if (xhr.readyState === 4 && xhr.status === 200) {
                        reslove(xhr);
                    } else if (xhr.readyState === 4) {
                        reject(xhr);
                    }
                };
            });
        } else {
            return await Promise.reject(
                "Your browser does not support XMLHTTP."
            );
        }
    }
}
